import xlsx from 'xlsx'
import { join } from 'path'
import fs from 'fs'
import express from 'express'
import cors from 'cors'
const app = express()
// 答题数据服务器的端口
const exceldataport = 3000

export function runDatiServer() {
  const workbook = xlsx.readFile(join(__dirname, '../../resources/题库.xlsx'))
  // 获取所有工作表的名字
  const sheetNames = workbook.SheetNames
  // 读取第一个工作表的数据
  const worksheet = workbook.Sheets[sheetNames[0]]
  // 将工作表数据转换为json格式
  const jsonData = xlsx.utils.sheet_to_json(worksheet, { header: 1 })
  let targetRows = jsonData.slice(1, jsonData.length)
  let selectedRows
  function getRandomRows(rows, count) {
    // 复制数组以避免修改原始数据
    let shuffled = rows.slice()
    // Fisher-Yates 洗牌算法
    for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1))
      ;[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
    }
    return shuffled.slice(0, count)
  }
  function removeElements(mainArray, elems2remove) {
    return mainArray.filter((item) => !elems2remove.includes(item))
  }
  function updateArray(i) {
    selectedRows = getRandomRows(targetRows, 10)
    targetRows = removeElements(targetRows, selectedRows)
    try {
      fs.writeFileSync(
        join(__dirname, `../../resources/database/database${i}.json`),
        JSON.stringify(selectedRows)
      )
      console.log('File wirten successfully')
    } catch (error) {
      console.log('File wirten error: ', error)
    }
  }

  for (let i = 0; i < 5; i++) {
    updateArray(i)
  }

  app.use(cors())
  app.get('/', (req, res) => {
    res.send(selectedRows)
  })
  app.get('/guanqia/:id', (req, res) => {
    fs.readFile(
      join(__dirname, `../../resources/database/database${req.params.id}.json`),
      function (err, data) {
        if (err) return
        res.send(JSON.parse(data))
      }
    )
  })
  app.listen(exceldataport, () => {
    console.log(`Server is running on port ${exceldataport}`)
  })
}
